
import React, { useEffect, useState, useRef } from 'react';
import sdk from 'qcloud-iotexplorer-h5-panel-sdk';
import { useDeviceData } from '../hooks/useDeviceData';
import { StandardBleConnector } from '../StandardBleDemo/components/leBleConnector - new';
import './DeviceDetailBtn.less';
import { useHistory } from "react-router-dom";
const imgrul = "https://iotapi.sziton.com/afile/J4GFRSTHQ4/"
export function DeviceDetail() {
  const [sdkReady, setSdkReady] = useState(false);
  const [state, {
    onDeviceDataChange,
    onDeviceStatusChange
  }] = useDeviceData(sdk);
  const history = useHistory()
  const weight_unit = state.templateMap.weight_unit.define.mapping
  const tempbattery_status = state.deviceData.battery_status == undefined ? "--" : state.deviceData.battery_status+'%'
  const unitindex = state.deviceData.weight_unit
  const [unit,setunit] = useState(weight_unit[unitindex])
  const [battery_status,setbattery_status] = useState(tempbattery_status)
  // 显示单位弹框
  const [isunit,setisunit] = useState(false)
  const [isconected,setisconected] = useState(true)
  // WebSocket 监听
  useEffect(() => {
    // 监听设备控制推送
    const handleWsControl = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('DeviceDetailBtn wsControl', deviceData);
    };
    // 监听设备上报数据推送
    const handleWsReport = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('DeviceDetailBtn wsReport', deviceId, deviceData);
    };
    // 监听设备在线状态变更推送
    const handleWsStatusChange = ({ deviceId, deviceStatus}) => {
      if (deviceId === sdk.deviceId) {
        onDeviceStatusChange(deviceStatus);
      }
      if (deviceStatus === 0){
        Bleref.current.disconnectDevice()
        sdk.reloadAfterUnmount()
      }
      console.error('DeviceDetailBtn wsStatusChange', deviceId, deviceStatus );
    };

    sdk
      .on('wsControl', handleWsControl)
      .on('wsReport', handleWsReport)
      .on('wsStatusChange', handleWsStatusChange);

    return () => {
      sdk
        .off('wsControl', handleWsControl)
        .off('wsReport', handleWsReport)
        .off('wsStatusChange', handleWsStatusChange);
    };
  }, []);
  useEffect(() =>  {
		h5PanelSdk.sdkReady().then(() =>  setSdkReady(true));
	}, []);
  useEffect(() => {
    setunit(weight_unit[state.deviceData.weight_unit])
    setbattery_status(
      state.deviceData.battery_status+'%'
    )
    console.error(state.deviceData.battery_status)
    console.error(state.deviceData.weight_unit)
    console.error(weight_unit)
  }, [state]);
  function showunit(){
    console.log(isunit)
    setisunit(true)
  }
  function YactionSheet(props){
    // 单位页面
    function WeuList() {
      return (
        <div>
          {
            Object.keys(weight_unit).map((obj, idx) => (
              <div className="fl-lr pdtb bd1 mgb" key={idx} onClick={() =>changeUnit(obj)} >
                <div>{weight_unit[obj]}</div>
                <div><input type="radio" name="weight_unit" defaultChecked={unitindex === idx} value={weight_unit[obj]}/></div>
              </div>
            ))
          }
        </div>
      )
    }
    const onControlDeviceData = (id, value) => sdk.controlDeviceData({ [id]: value });
    const changeUnit = async (value) => {
      console.log(`selected ${value}`);
      if(value == 2){value = 3}
      await onControlDeviceData("weight_unit",value)
      setisunit(false)
      setunit(weight_unit[value])
    }
    console.log(props)
    const title =props.title
    const isshow = props.show
    function close(){
      setisunit(false)
    }
    function cofirm(){
      onControlDeviceData("weight_unit",value)
    }
    function cancle(){
      setisunit(false)
    }
    return (
      <>
      {isunit &&
      <div className="acsheel-con">
        <div className="acsheel">
          <div className="acsheel-head">
            <div className="actitle">{title}</div>
            <div className="acclose" onClick={close}>X</div>
          </div>
          <div className="acsheeltem">
            <div className="acitem">
              <WeuList />
            </div>
            {/* <div className="acsheel-foot">
              <div className="lfbtn-gr mgr" onClick={cancle}>取消</div>
              <div className="lfbtn mgl" onClick={cofirm}>确定</div>
            </div> */}
          </div>
        </div>
      </div>}
      </>
    )
  }
  const isStandardBleDevice = sdk.isStandardBleDevice;
  const Bleref = useRef()
  let bleStatus = Bleref.current == undefined ? "" : Bleref.current.connectStatusInfo.status
  const deldevt = async () => {
    console.error(Bleref)
    if (Bleref.current.connectStatusInfo.status!="connected"){
			sdk.tips.show("请先连接蓝牙设备！")
		} else {
      // const isConfirm = await sdk.tips.showModal({
      //   title: "删除设备提醒",
      //   content: '请确保当前设备已连接蓝牙，若未连接蓝牙删除设备将需要重置设备才可重新配网！',
      //   showCancel: true,
      //   cancelText: "关闭提醒",
      //   cancelColor: "black",
      //   confirmText: "继续删除",
      //   confirmColor: "red",
      // })
      // if (isConfirm) {
        await Bleref.current.deleteDevice()
        await sdk.reloadAfterUnmount()
        // await sdk.deleteDevice()
        await sdk.tips.show("删除成功！")
        await sdk.navBack()
      // }
    }
  }
  return  !sdkReady ? <div > loading...</div >  : (
    <div className="detailpage">
    {isconected && (
      <div className="bleconecter">
        {isStandardBleDevice &&
          (<StandardBleConnector familyId={sdk.familyId} deviceId={sdk.deviceId} ref={Bleref}/>)
        }
      </div>
    )}
    <div className="itemlist pdtb">
      <div className="fl-rsbc bd1 pd bdwhite" onClick={()=>sdk.goEditDeviceNamePage()}>
        <div className="ilimg fl-rc"><span>设备名称</span></div>
        <div className="r-img">{sdk.deviceInfo.AliasName}<img src={imgrul+"arrow-r.png"}/></div>
      </div>
      <div className="fl-rsbc bd1 pd bdwhite" onClick={()=>sdk.goDeviceInfoPage()}>
        <div className="ilimg fl-rc"><span>设备信息</span></div>
        <div className="r-img">{sdk.deviceName}<img src={imgrul+"arrow-r.png"}/></div>
      </div>
      <div className="fl-rsbc bd1 pd bdwhite" onClick={()=>sdk.goRoomSettingPage()}>
        <div className="ilimg fl-rc"><span>房间设置</span></div>
        <div className="r-img">{sdk.roomName}<img src={imgrul+"arrow-r.png"}/></div>
      </div>
      <div className="fl-rsbc bd1 pd bdwhite" onClick={()=>sdk.goShareDevicePage()}>
        <div className="ilimg fl-rc"><span>设备分享</span></div>
        <div className="r-img"><img src={imgrul+"arrow-r.png"}/></div>
      </div>
      <div className="fl-rsbc bd1 pd bdwhite" onClick={()=>sdk.goFirmwareUpgradePage()}>
        <div className="ilimg fl-rc"><span>固件升级</span></div>
        <div className="r-img"><img src={imgrul+"arrow-r.png"}/></div>
      </div>
      <div className="fl-rsbc bd1 pd bdwhite">
        <div className="ilimg fl-rc"><span>电量状态</span></div>
        <div className="r-img">{battery_status}</div>
      </div>
      <div className="fl-rsbc bd1 pd bdwhite" onClick={showunit}>
        <div className="ilimg fl-rc"><span>重量单位</span></div>
        <div className="r-img">{unit}</div>
      </div>
    </div>
    <div className="pdb fl-cc">
      <div className="lfbtn-red" onClick={deldevt}>删除设备</div>
    </div>
    <div className="pdb fl-cc">
      <div className="lfbtn-white" onClick={()=>{history.replace("/Home")}}>关闭设备详情</div>
    </div>
    {isunit && (
      <YactionSheet title={"修改单位"} show={true}/>
    )}
    </div>
  );
}
